
import { ShoppingService } from 'admin/services/shopping';
import * as wz from 'myWuZhui';
import { FormValidator, rules as r } from "maishu-dilu";
import React = require('react');
import ReactDOM = require('react-dom');
import * as wuzhui from "maishu-wuzhui";
import * as chitu from "maishu-chitu";

export default function (page: chitu.Page) {

    let shopping = page.createService(ShoppingService);

    class SolutionListPage extends React.Component<any, any>{
        private validator: FormValidator;
        private gridViewElement: HTMLTableElement;
        private dialogElement: HTMLElement;
        dataSource: wuzhui.DataSource<any>;
        items = new Array<FreightSolution>();

        constructor(props) {
            super(props);
        }
        componentDidMount() {
            let dataSource = this.dataSource = new wuzhui.DataSource({
                select: async () => {
                    let dataItems = await shopping.freightSolutions();
                    return { dataItems, totalRowCount: dataItems.length };
                },
                delete: (dataItem) => shopping.deleteFreightSolution(dataItem),
                update: (dataItem) => shopping.updateFreightSolution(dataItem),
                insert: (dataItem) => shopping.addFreightSolution(dataItem),
                primaryKeys: ['Id']
            });

            dataSource.selected.add((sender, result) => {
                this.items = result.dataItems;
            })

            let it = this;
            let gridView = wz.createGridView({
                element: this.gridViewElement,
                columns: [
                    new wz.BoundField({
                        dataField: 'Id', headerText: '编号',
                        headerStyle: { width: '300px' } as CSSStyleDeclaration
                    }),
                    new wz.BoundField({
                        dataField: 'Name', headerText: '名称',
                    }),
                    new wz.CustomField({
                        createItemCell(dataItem) {
                            let cell = new IsDefaultCell(it, dataItem)
                            return cell;
                        },
                        itemStyle: { textAlign: 'center', width: '100px' } as CSSStyleDeclaration,
                        headerText: '是否默认'
                    }),
                    new wz.CustomField({
                        createItemCell(dataItem) {
                            let cell = new wuzhui.GridViewCell();
                            ReactDOM.render(
                                <div>
                                    <button className="btn btn-info btn-minier" style={{ marginRight: 4 }}
                                        onClick={() => it.showDialog(dataItem)}>
                                        <i className="icon-pencil"></i>
                                    </button>
                                    <button className="btn btn-minier btn-danger" style={{ marginRight: 4 }}
                                        ref={(e: HTMLElement) => {
                                            if (!e) return;
                                            e.onclick = ui.buttonOnClick(() => dataSource.delete(dataItem),
                                                { confirm: `确定要删除'${dataItem.Name}'运费方案吗` });
                                        }}>
                                        <i className="icon-trash"></i>
                                    </button>
                                    <a className="btn btn-info btn-minier" style={{ marginRight: 4 }}
                                        href={`#freight_freightList?id=${dataItem.Id}&name=${encodeURI(dataItem.Name)}`}>设置运费</a>
                                </div>, cell.element);
                            return cell;
                        },
                        headerText: '操作',
                        headerStyle: { width: '180px' } as CSSStyleDeclaration,
                        itemStyle: { textAlign: 'center' } as CSSStyleDeclaration,
                    })
                ],
                dataSource,
                pageSize: null
            });
        }
        showDialog(dataItem?: FreightSolution) {
            let name: string = dataItem ? dataItem.Name : '';
            let defaultFreight: number;
            let title = dataItem ? '编辑运费模板' : '添加运费模板';

            let fields = [
                { name: 'name', rules: [r.required('请输入运费模板名称')] },
            ];

            if (!dataItem) {
                fields.push({ name: 'freight', rules: [r.required('请输入默认运费')] });
            }

            this.validator = new FormValidator(this.dialogElement, ...fields);
            ReactDOM.render(
                <div className="modal-dialog">
                    <div className="modal-content">
                        <div className="modal-header">
                            <button type="button" className="close" data-dismiss="modal">
                                <span aria-hidden="true">&times;</span>
                                <span className="sr-only">Close</span>
                            </button>
                            <h4 data-bind="text:title" className="modal-title">{title}</h4>
                        </div>
                        <div className="modal-body form-horizontal">
                            <div className="form-group">
                                <label className="col-sm-2 control-label">名称</label>
                                <div className="col-sm-10">
                                    <input name="name" type="text" className="form-control"
                                        placeholder="请输入运费模板的名称"
                                        ref={(e: HTMLInputElement) => {
                                            if (!e) return;
                                            e.value = name || '';
                                        }}
                                        onChange={(e) => name = (e.target as HTMLInputElement).value} />
                                </div>
                            </div>
                            {dataItem == null ? <div className="form-group">
                                <label className="col-sm-2 control-label">默认运费</label>
                                <div className="col-sm-10">
                                    <input name="freight" type="text" className="form-control" placeholder="在模板下，适用于大部分地区的运费"
                                        onChange={(e) => defaultFreight = Number.parseFloat((e.target as HTMLInputElement).value)} />
                                </div>
                            </div> : null}
                            <div className="modal-footer">
                                <button name="btn_cancel" type="button" className="btn btn-default" data-dismiss="modal">取消</button>
                                <button name="btn_confirm" type="button" className="btn btn-primary"
                                    ref={(e: HTMLButtonElement) => {
                                        if (!e) return;
                                        ui.buttonOnClick(e, async () => {
                                            let isValid = await this.validator.check();
                                            if (!isValid) {
                                                return Promise.reject('Valid fail.');
                                            }
                                            if (dataItem) {
                                                dataItem.Name = name;
                                                this.dataSource.update(dataItem).then(() => {
                                                    ui.hideDialog(this.dialogElement);
                                                });
                                            }
                                            else {
                                                let freightElement = this.dialogElement.querySelector('[name="freight"]') as HTMLInputElement;
                                                dataItem = {
                                                    Name: name, IsDefault: false,
                                                    defaultFreight: Number.parseFloat(freightElement.value)
                                                };
                                                this.dataSource.insert(dataItem).then(() => {
                                                    ui.hideDialog(this.dialogElement);
                                                });
                                            }

                                        })
                                    }}>确认</button>
                            </div>
                        </div>
                    </div>
                </div>
                , this.dialogElement);


            ui.showDialog(this.dialogElement)
        }
        render() {
            return (
                <div>
                    <div id="news" className="tabbable">
                        <ul id="myTab" className="nav nav-tabs">
                            <li className="pull-right">
                                <button data-bind="click:newItem" className="btn btn-primary btn-sm"
                                    onClick={() => this.showDialog()}>
                                    <i className="icon-plus"></i>
                                    <span>新建运费模板</span>
                                </button>
                            </li>
                        </ul>
                    </div>
                    <table ref={(e: HTMLTableElement) => this.gridViewElement = e || this.gridViewElement}>
                    </table>
                    <div className="modal fade" ref={(e: HTMLElement) => this.dialogElement = e || this.dialogElement}>
                    </div>
                </div>
            );
        }
    }

    ReactDOM.render(<SolutionListPage />, page.element);


    class IsDefaultCell extends wuzhui.GridViewDataCell<FreightSolution> {
        // dataItem: FreightSolution;
        solutionListPage: SolutionListPage;
        constructor(solutionListPage: SolutionListPage, dataItem: FreightSolution) {
            super({
                render: (dataItem) => this.renderDataItem(dataItem)
            })
            // this.dataField = 'IsDefault';
            this.solutionListPage = solutionListPage;
            // this.dataItem = dataItem;
        }
        renderDataItem(dataItem: FreightSolution) {
            let value = dataItem.IsDefault;
            ReactDOM.render(value != true ?
                <button className="btn btn-minier btn-primary"
                    ref={(e: HTMLButtonElement) => {
                        if (!e) return;
                        ui.buttonOnClick(e, async () => {
                            let shopping = page.createService(ShoppingService);

                            let it = this.solutionListPage;
                            let result = await shopping.setDefaultFreightSolution(dataItem.Id);
                            dataItem.IsDefault = true;
                            it.items.forEach(item => {
                                item.IsDefault = item == dataItem;
                                it.dataSource.updated.fire(it.dataSource, item);
                            })
                            return result;
                        })
                    }}>设为默认 </button> :
                <span>默认方案</span>,
                this.element
            );
        }
    }


}

